package cn.regexp.greenway.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpStatus;
import cn.regexp.greenway.pojo.Route;
import cn.regexp.greenway.service.RouteService;
import cn.regexp.greenway.utils.DistanceUtils;
import cn.regexp.greenway.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 路线相关的业务
 */
@RestController
@RequestMapping("route")
public class RouteController {

    @Autowired
    private RouteService routeService;

    /**
     * 创建路线
     *
     * @return
     */
    @PostMapping
    public Object createRoute() {
        String routeId = this.routeService.createRoute();
        if (null != routeId) {
            //创建成功
            return MapUtil.builder("routeId", routeId).build();
        }
        //创建失败
        return ErrorResult.builder()
                .errCode("500")
                .errMessage("创建路线失败！").build();
    }

    /**
     * 删除路线
     *
     * @param routeId
     * @return
     */
    @DeleteMapping("{routeId}")
    public Object deleteRoute(@PathVariable("routeId") String routeId) {
        Boolean result = this.routeService.deleteRoute(routeId);
        if (result) {
            //删除成功
            return null;
        }
        //删除失败
        return ErrorResult.builder()
                .errCode(String.valueOf(HttpStatus.HTTP_BAD_REQUEST))
                .errMessage("删除路线失败！").build();
    }

    /**
     * 更新路线（结束运动）
     * @param routeId   路线ID
     * @param title     路线标题
     * @return
     */
    @PutMapping
    public Object updateRoute(@RequestParam("routeId") String routeId, @RequestParam("title") String title) {
        return routeService.updateRoute(routeId, title);
    }

    @GetMapping("{routeId}")
    public Object queryRoute(@PathVariable("routeId") String routeId,
                             @RequestParam("longitude") Double longitude,
                             @RequestParam("latitude") Double latitude) {
        Route route = this.routeService.queryRouteById(routeId);
        if (route != null) {
            // 计算当前用户与路线的距离
            double distance = DistanceUtils.getDistance(longitude, latitude,
                    route.getLocation().getX(), route.getLocation().getY());
            route.setRouteDistance(distance);
            return route;
        }
        return ErrorResult.builder()
                .errCode(String.valueOf(HttpStatus.HTTP_BAD_REQUEST))
                .errMessage("路线不存在！").build();
    }

}
